import 'dart:convert';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:carousel_slider/carousel_controller.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/base/base_page_controller.dart';
import 'package:flutter_changdian_football/config/enum/refresh.dart';
import 'package:flutter_changdian_football/model/other/index_page_base_info_model.dart';
import 'package:flutter_changdian_football/model/other/location_model.dart';
import 'package:flutter_changdian_football/model/other/news_model.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/utils/ext/refresher_extension.dart';
import 'package:flutter_changdian_football/utils/share_util.dart';
import 'package:flutter_changdian_football/utils/show_sheet_utils.dart';
import 'package:flutter_changdian_football/utils/str_utils.dart';
import 'package:flutter_changdian_football/widget/screenutil/custom_screenutil.dart';
import 'package:flutter_changdian_football/widget/sheet/share_icon_sheet.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pickers/address_picker/locations_data.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

class HomeController extends BaseGetPageController {
  static HomeController get to => Get.find();

  final CarouselController carouselController = CarouselController();

  int currentBannerIndex = 0;
  changeBannerIndex(p) {
    currentBannerIndex = p;
    update();
  }

  @override
  void onInit() {
    super.onInit();

    setDefaultLocation();

    indexPageBaseInfoModel = IndexPageBaseInfoModel.fromJson(initData);
    update();

    indexPageBaseInfo();

    eventBus.on<BottomNavigationBarEvent>().listen((event) {
      if (event.message == CustomConstant.EVENT_REFRESH) {
        // 刷新数据
        indexPageBaseInfo();
      } else if (event.message == CustomConstant.EVENT_LOGOUT_REFRESH) {
        indexPageBaseInfoModel?.waitReadMessageNum = 0;
        update();
      } else if (event.message == CustomConstant.EVENT_SIGNLE_MESSAFE_NUM) {
        indexPageBaseInfoModel?.waitReadMessageNum = (indexPageBaseInfoModel?.waitReadMessageNum ?? 0) -1;
        update();
      } else if (event.message == CustomConstant.EVENT_ALL_MESSAGE_NUM) {
        indexPageBaseInfoModel?.waitReadMessageNum = 0;
        update();
      }
    });
  }

  IndexPageBaseInfoModel? indexPageBaseInfoModel;

  /// 初始化数据
  Map<String, dynamic> initData = {
		"features": [
			{
				"iconUrl": "http://changdian-foot.oss-cn-hangzhou.aliyuncs.com/features_icon/local_court.png",
				"featuresName": "本地场地",
				"redirectUrl": "http://npsadmin.ypnps.cn/?targetPage=LocalCourt",
				"jumpType": "APP",
				"shareDetail": null,
				"sequence": 1,
				"isShow": true
			},
			{
				"iconUrl": "http://changdian-foot.oss-cn-hangzhou.aliyuncs.com/features_icon/club_rank.png",
				"featuresName": "俱乐部排行",
				"redirectUrl": "http://npsadmin.ypnps.cn/?targetPage=ClubRanking",
				"jumpType": "APP",
				"shareDetail": null,
				"sequence": 2,
				"isShow": true
			},
			{
				"iconUrl": "http://changdian-foot.oss-cn-hangzhou.aliyuncs.com/features_icon/invite_teammates.png",
				"featuresName": "邀请好友",
				"redirectUrl": null,
				"jumpType": "SHARE",
				"shareDetail": null,
				"sequence": 3,
				"isShow": true
			},
			{
				"iconUrl": "https://changdian-foot.oss-cn-hangzhou.aliyuncs.com/features_icon/fame_hall.png",
				"featuresName": "名人堂",
				"redirectUrl": "http://npsadmin.ypnps.cn/?targetPage=HallOfFame",
				"jumpType": "APP",
				"shareDetail": null,
				"sequence": 4,
				"isShow": true
			}
		],
		"carousels": [
			{
				"showImg": "http://changdian-foot.oss-cn-hangzhou.aliyuncs.com/carousel_img/1.png",
				"redirectUrl": null,
				"redirectType": "APP",
				"sequence": 1
			},
		],
		"waitReadMessageNum": 0
	};

  /// 获取首页基本信息
  indexPageBaseInfo() async {
    var resp = await ReqOther.indexPageBaseInfo();
    if (resp.status == Status.completed) {
      if (resp.data['code'] == '200') {
        indexPageBaseInfoModel = IndexPageBaseInfoModel.fromJson(resp.data['data']);
        update();
      }
    }
    update();
  }


  // 分享
  shareImg() async {
    try {
      EasyLoading.show();
      var resp = await ReqOther.getProtocol(CustomConstant.SHARE_IMAGE);

      if (resp.data['code'] == '200') {
        ShareIconSheet.shareIcon(
          null, 
          null, 
          resp.data['data']['url'], 
          null,
          isShowImg: true,
          wxTap: () {
            ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "0");
          },
          pyqTap: () {
            ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "1");
          },
          qqTap: () {
            ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "2");
          },
          wbTap: () {
            ShareUtil.shareImg(title: '分享图片URL', description: '分享图片URL',  image: resp.data['data']['url'], shareType: "3");
          },
        );
        update();
      } else {
        CustomToast.showTextToast(resp.data['msg']);
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  List<NewsModel> newsModelList = [];

  @override
  void requestData(
    RefreshController controller, 
    {
      Refresh refresh = Refresh.first
    }
  ) async {
    var response = await ReqOther.newsList(
      pageNum: page,
    );

    if (response.status == Status.completed) {
      if (response.data['code'] == '200') {
        /// 判断是否为最后一页, 如果是， over传true， 否则false
        if (response.data['data']['hasNextPage'] == false) {
          RefreshExtension.onSuccess(controller, refresh, true); 
        } else {
          RefreshExtension.onSuccess(controller, refresh, false);
        }
        

        /// 下拉刷新需要清除列表
        if (refresh != Refresh.down) {
          newsModelList.clear();
          update();
        }

        for (int i = 0; i < response.data['data']['newsVOList'].length; i++) {
          newsModelList.add(NewsModel.fromJson(response.data['data']['newsVOList'][i]));
        }

        showSuccess(newsModelList);
        update();
      } else {
        showError();  
        RefreshExtension.onError(controller, refresh);
      }
    } else {
      showError();  
      RefreshExtension.onError(controller, refresh);
    }
  }

  LocationModel? locationModel;

  /// 设置地址
  setDefaultLocation() async {
    // SpUtil.remove('localAddress');
    String localAddress = SpUtil.getString('localAddress') ?? '';
    if (localAddress.isEmpty) {
      locationModel = LocationModel.fromJson({
        "province": "重庆市",
        "district": "渝北区",
        "pcode": "500112"
      });
      SpUtil.putObject('localAddress', jsonEncode(locationModel!.toJson()));
      update();
    } else {
      locationModel = LocationModel.fromJson(jsonDecode(jsonDecode(localAddress)));

      longitude = SpUtil.getString('longitude');
      latitude = SpUtil.getString('latitude');
      update();
    }
  }

  static pickerStyle() {
    return PickerStyle(
      cancelButton: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Text('取消',style: TextStyle(color: const Color(0xffcccccc), fontSize: 16.sp),),
      ),
      commitButton: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.w), 
        child: Text('确定', style: TextStyle(color: const Color(0xff499360), fontSize: 16.sp),)
      ),
      textSize: 14.sp,
    );
  }

  /// 切换地址
  changeDefaultLocation() {
    Pickers.showAddressPicker(
      Get.context!,
      initProvince: locationModel?.province ?? '',
      initCity: locationModel?.district ?? '',
      addAllItem: false,
      onConfirm: (province, city, district) {
        List<String> codeList = Address.getCityCodeByName(provinceName: '${province}', cityName: '${city}');
        locationModel = LocationModel.fromJson({
          "province": province,
          "district": city,
          "pcode": codeList[1]
        });
        SpUtil.putObject('localAddress', jsonEncode(locationModel!.toJson()));
        update();
      },
      pickerStyle: pickerStyle()
    );
  }


  String? latitude;
  String? longitude;

  toPage(url, type) async {
    bool cacheAddress = SpUtil.getBool('cacheAddress') ?? false;
    if (cacheAddress == true) {
      StrUtils.jumpByUrl(url, type);
      // _startLocation(url, type);
      return ;
    }
    Permission permission = Permission.location;
    if (!await permission.isGranted) {
      ShowSheetUtils.show(
        '为了给您提供准确有效的足球场以及俱乐部信息，请授权“畅点足球”APP使用您的定位信息',
        onTap: () async {
          if (await checkPermission() == true) {
            EasyLoading.show();
            _startLocation(url, type);
          } else {
            SpUtil.putBool('cacheAddress', true);
            StrUtils.jumpByUrl(url, type);
          }
        },
        onCleanTap: () async {
          EasyLoading.show();
          await Future.delayed(const Duration(milliseconds: 500));
          SpUtil.putBool('cacheAddress', true);
          StrUtils.jumpByUrl(url, type);
          EasyLoading.dismiss();
        }
      );
    } else {
      // 定位
      EasyLoading.show();
      _startLocation(url, type);
    }
    
  }

  /// 检查是否有定位权限
  Future<bool> checkPermission() async {
    Permission permission = Permission.location;

    if (!await permission.isGranted) {
      PermissionStatus status = await permission.request();

      if (status.isPermanentlyDenied && Platform.isIOS) {
        return true;
      } else if (status != PermissionStatus.granted) {
        return false;
      }
    }

    return true;
  }

  _startLocation(url, type) {
    AMapFlutterLocation _flutterLocation = AMapFlutterLocation();
    _flutterLocation.onLocationChanged().listen((event) async {
      var code = event['errorCode'];
      await Future.delayed(const Duration(milliseconds: 500)); 
      // logger.d(event);
      // EasyLoading.dismiss();
      // return ;
      if (code == null || code == 0) {
        SpUtil.putBool('cacheAddress', true);

        _flutterLocation.stopLocation();
        EasyLoading.dismiss();

        if (event['province'] == '重庆市' || event['province'] == '北京市' || event['province'] == '天津市' || event['province'] == '上海市') {
          List<String> codeList = Address.getCityCodeByName(provinceName: '${event['province']}', cityName: '${event['district']}');

          logger.d(codeList);
          locationModel = LocationModel.fromJson({
            "province": event['province'],
            "district": event['district'],
            "pcode": codeList[1]
          });
          latitude = '${event['latitude']}';
          longitude = '${event['longitude']}';
          SpUtil.putString('latitude', '${event['latitude']}');
          SpUtil.putString('longitude', '${event['longitude']}');

          SpUtil.putObject('localAddress', jsonEncode(locationModel!.toJson()));
          update();
        } else {
          List<String> codeList = Address.getCityCodeByName(provinceName: '${event['province']}', cityName: '${event['city']}');

          locationModel = LocationModel.fromJson({
            "province": event['province'],
            "district": event['city'],
            "pcode": codeList[1]
          });
          latitude = '${event['latitude']}';
          longitude = '${event['longitude']}';
          SpUtil.putString('latitude', '${event['latitude']}');
          SpUtil.putString('longitude', '${event['longitude']}');

          SpUtil.putObject('localAddress', jsonEncode(locationModel!.toJson()));
          update();
        }

        StrUtils.jumpByUrl(url, type);
      } else {
        EasyLoading.dismiss();
      }
      
    });
    AMapLocationOption _option = AMapLocationOption(onceLocation: true);
    _flutterLocation.setLocationOption(_option);
    _flutterLocation.startLocation();
  }


}